package com.yycx.module.file.provider.listener;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.QueueConstants;
import com.yycx.module.file.provider.service.SysFileService;
import com.yycx.starter.rabbitmq.config.RabbitComponent;
import com.yycx.starter.rabbitmq.core.BaseRabbiMqHandler;
import com.yycx.starter.rabbitmq.listener.MqListener;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;

import java.util.List;

/**
 * 更新文件业务ID
 *
 * @author zyf
 */
@RabbitComponent(value = "updateFileBusIdRabbitMqListener")
public class UpdateFileBusIdRabbitMqListener extends BaseRabbiMqHandler<EntityMap> {

    @Autowired
    private SysFileService fileService;

    @RabbitListener(queues = QueueConstants.QUEUE_UPLOADFILE)
    public void onMessage(EntityMap baseMap, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        super.onMessage(baseMap, deliveryTag, channel, new MqListener<EntityMap>() {
            @Override
            public void handler(EntityMap map, Channel channel) {
                Long busId = map.getLong("busId");
                String entityName = map.get("entityName");
                Long[] fileIds = map.get("fileIds");
                Long[] removeIds = map.get("removeIds");
                try {
                    List<EntityMap> files = fileService.selectDeleteFileList(removeIds, busId, entityName);
                    if (FlymeUtils.isNotEmpty(removeIds)) {
                        for (EntityMap sysFile : files) {
                            String filePath = sysFile.get("localPath");
                            Long fileId = sysFile.getLong("fileId");
                            if (FlymeUtils.isNotEmpty(filePath)) {
                                //filePath = filePath.substring(0, filePath.indexOf(fileId.toString()) + 20);
                            }
                            cn.hutool.core.io.FileUtil.del(filePath);
                            fileService.removeById(fileId);
                        }
                    }
                    if (FlymeUtils.isNotEmpty(fileIds)) {
                        UpdateWrapper u = new UpdateWrapper();
                        u.set(true, "busId", busId);
                        u.set(true, "busType", entityName);
                        u.in("fileId", fileIds);
                        fileService.update(u);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
